<template>
  <userManageView
    :isLoading="isLoading"
    :isFirst="isFirst"
    :tableData="tableData"
    :tableDataRole="tableDataRole"
    :tableDataSystem="tableDataSystem"
    :total="total"
    :pageSize="pageSize"
    :dialogAddUser="dialogAddUser"
    :dialogEditUser="dialogEditUser"
    :userForm="userForm"
    :stationList="stationList"
    :selectItemData="selectItemData"
    :selectItemIndex="selectItemIndex"
    :currentPage="currentPage"
    :dialogEditRoles="dialogEditRoles"
    :rolesForm="rolesForm"
    :rolesList="rolesList"
    :dialogSysUser="dialogSysUser"
    :sysUserForm="sysUserForm"
    :sysUserTypeList="sysUserTypeList"
    :dialogSysUserEdit="dialogSysUserEdit"
    :joinStationList="joinStationList"
    @tabsClick="tabsClick"
    @changePage="changePage"
    @sizeChange="sizeChange"
    @addUser="addUser"
    @editUser="editUser"
    @addUserCancel="addUserCancel"
    @addUserSure="addUserSure"
    @addUserClose="addUserClose"
    @editUserKeep="editUserKeep"
    @delUser="delUser"
    @editUserClose="editUserClose"
    @rowClickUser="rowClickUser"
    @addNewRole="addNewRole"
    @addRolesClose="addRolesClose"
    @addRolesKeep="addRolesKeep"
    @makeSysUser="makeSysUser"
    @sysUserClose="sysUserClose"
    @addSysUserKeep="addSysUserKeep"
    @delSysUser="delSysUser"
    @editSysUser="editSysUser"
    @sysUserEditClose="sysUserEditClose"
    @sysUserEditKeep="sysUserEditKeep"
    @changeStation="changeStation"
    @findUser="findUser"
    ref="userManage"
  ></userManageView>
</template>

<script>
  import userManageView from './userManageView';

  export default {

    components: {
      userManageView
      // name
    },
    name: "userManageLogic",
    props: {
      // msg: String //  [name: typeof]
    },
    filters: {},
    computed: {},
    watch: {},
    data() {
      return {
        isLoading: false,
        isFirst: true, // 是否是用户管理
        tableData: [], // 用户列表数据
        total: 0, // 总条数
        pageSize: 10, // 每页条数
        dataUserList: [], // 存储用户列表数据
        currentPage: 1, // 默认当前页
        tableDataRole: [], // 根据userid获取的角色列表
        tableDataSystem: [],
        dialogAddUser: false, // 添加用户弹窗显隐状态
        dialogEditUser: false, // 编辑用户弹窗显隐状态
        selectItemData: {}, // 选中行的数据
        selectItemIndex: "-1", // 选中行的下标
        userForm: {
          name: '',
          desc: '',
          phone: '',
          station: [],
          inposition: "",
          // cardNum: "",
          // passNum: "",
          jobNum: ""
        },
        stationList: [], // 岗位列表
        dialogEditRoles: false, // 添加角色弹窗
        rolesForm: {
          roles: ""
        },
        rolesList: [], // 获取角色id
        dialogSysUser: false, // 开通系统账户弹窗的显隐
        sysUserForm: {
          name: "",
          password: "",
          // agamePassword: "",
          type: ""
        },
        sysUserTypeList: [],
        dialogSysUserEdit: false,
        editSysUserInfo: {}, // 存放编辑账户的行数据
        keepStationMap: new Map(),
        joinStationList: [] // 在职岗位列表
      }
    },
    created() {
      this.getUserList();
      this.getRoleList();
      this.getDict();
    },
    mounted() {

    },
    methods: {
      async getUserList(obj) {
        this.isLoading = true;
        let res = await _https.post.getAllPosition();
        if (res.data.code == 0) {
          this.stationList = res.data.data;
        } else {
          this.$message({type: 'error', message: res.data.message});
        }

        res = await _https.post.getUserList(obj);
        if (res.data.code == 0) {
          let data = res.data.data;
          let newContent = [...data];
          let stationMap = new Map();
          let stationList = this.stationList;
          for (let i = 0; i < stationList.length; i++) {
            stationMap.set(stationList[i].id, stationList[i].name);
            this.keepStationMap.set(stationList[i].id, stationList[i]);
          }
          let newArr = newContent.map((item) => {
            let newPosition = item.position ? item.position.split(",") : [];
            let poName = "";
            for (let i = 0; i < stationList.length; i++) {
              for (let j = 0; j < newPosition.length; j++) {
                if (newPosition[j] == stationList[i].id) {
                  poName += "," + stationMap.get(stationList[i].id);
                }
                item.poName = poName.substring(1);
              }
              if (item.inposition == stationList[i].id) {
                item.inpositionName = stationList[i].name;
              }
            }
            return item;
          });

          this.dataUserList = newArr;
          let currentPage = this.currentPage;
          if (data.length % this.pageSize == 0 && currentPage != 1) {
            currentPage = Math.ceil(data.length / this.pageSize);
            this.currentPage = currentPage;
          }
          this.setDataList(currentPage);
          this.total = data.length;
          this.isLoading = false;
        } else {
          this.$message({type: 'error', message: res.data.message});
        }
      },
      getRoleList() {
        _https.post.getRoleList().then(res => {
          if (res.data.code == 0) {
            this.rolesList = res.data.data;
          } else {
            this.$message({type: 'error', message: res.data.message});
          }
        })
      },
      getDict() {
        let obj = {
          datatype: "account"
        };
        _https.post.getDict(obj).then(res => {
          if (res.data.code == 0) {
            this.sysUserTypeList = res.data.data;
          } else {
            this.$message({type: 'error', message: res.data.message});
          }
        });
      },
      /**
       * 将返回的数据进行分页操作
       * @param currentPage {Number}
       */
      setDataList(currentPage) {
        let current = currentPage * this.pageSize;
        let currentStart = current - this.pageSize;
        let currentEnd = current;
        this.tableData = this.dataUserList.slice(currentStart, currentEnd);
      },
      // 查询用户
      findUser(userSeach) {
        this.currentPage = 1;
        let obj = {
          name: userSeach
        };
        this.getUserList(obj);
      },
      /**
       * 分页改变当前页触发
       * @param page 返回值参数（当前页）
       */
      changePage(page) {
        this.currentPage = page;
        this.selectItemIndex = "-1";
        this.selectItemData = {};
        this.reset();
        this.setDataList(page);
      },
      sizeChange(num) {
        this.pageSize = num;
        this.getUserList();
      },
      tabsClick(tab, event) {
        this.isFirst = tab.index == 0 ? true : false;
      },
      // 添加用户
      addUser() {
        this.dialogAddUser = true;
        if (this.$refs.userManage.$refs.addUserForm) {
          this.$refs.userManage.$refs.addUserForm.resetFields();
        }
        this.userForm = {
          name: "",
          desc: "",
          phone: "",
          station: [],
          inposition: "",
          cardNum: "",
          passNum: "",
          jobNum: ""
        }
      },
      // 编辑用户
      editUser(index, row) {
        this.dialogEditUser = true;
        this.selectItemData = row;
        let selectItemData = row;
        this.joinStationList = [];
        let arr = selectItemData.position ? selectItemData.position.split(',') : [];

        for (let i = 0; i < arr.length; i++) {
          if (this.keepStationMap.get(arr[i])) {
            this.joinStationList.push(this.keepStationMap.get(arr[i]));
          }
        }

        this.userForm = {
          name: selectItemData.name,
          desc: selectItemData.description,
          phone: selectItemData.phone,
          station: selectItemData.position ? selectItemData.position.split(',') : [],
          inposition: selectItemData.inposition,
          cardNum: selectItemData.cardNum,
          passNum: selectItemData.passNum,
          jobNum: selectItemData.jobNum
        }
      },
      // 取消添加用户
      addUserCancel() {
        this.dialogAddUser = false;
      },
      // 关闭添加用户弹窗的回调
      addUserClose() {
        this.dialogAddUser = false;
        this.$refs.userManage.$refs.addUserForm.resetFields();
        this.reset();
      },
      // 确定添加用户
      addUserSure() {
        let userForm = this.userForm;
        let newObj = {
          description: userForm.desc,
          name: userForm.name,
          niname: "",
          logo: "",
          phone: userForm.phone,
          position: userForm.station.length != 0 ? userForm.station.join(',') : "",
          show: 1,
          inposition: userForm.inposition,
          jobnum: userForm.jobNum
        };

        this.$refs.userManage.$refs.addUserForm.validate((valid) => {
          if (!valid) {
            return;
          } else {
            _https.post.getSaveUser(newObj).then(res => {
              if (res.data.code == 0) {
                this.$message({type: 'success', message: res.data.message});
                this.getUserList();
                this.dialogAddUser = false;
              } else {
                this.$message({type: 'error', message: res.data.message});
              }
            })
          }
        })
      },
      // 编辑用户保存
      editUserKeep() {
        let selectItemData = this.selectItemData;
        let userForm = this.userForm;
        let newObj = {
          id: selectItemData.id,
          description: userForm.desc,
          name: userForm.name,
          logo: "",
          niname: "",
          phone: userForm.phone,
          position: userForm.station.length != 0 ? userForm.station.join(',') : "",
          show: 1,
          registdate: selectItemData.regist_date,
          inposition: userForm.inposition,
          jobnum: userForm.jobNum
        }

        this.$refs.userManage.$refs.editUserForm.validate((valid) => {
          if (!valid) {
            return;
          } else {
            _https.post.getUpdateUser(newObj).then(res => {
              if (res.data.code == 0) {
                this.$message({type: 'success', message: res.data.message});
                this.getUserList();
                this.selectItemIndex = "-1";
                this.dialogEditUser = false;
              } else {
                this.$message({type: 'error', message: res.data.message});
              }
            })
          }
        })
      },
      // 删除用户
      delUser(index, row) {
        let newObj = {
          id: row.id
        };
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _https.post.getDeleteUser(newObj).then(res => {
            if (res.data.code == 0) {
              this.$message({type: 'success', message: res.data.message});
              this.getUserList();
              this.dialogEditUser = false;
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 关闭编辑用户弹窗的回调
      editUserClose() {
        this.dialogEditUser = false;
        this.reset();
        this.$refs.userManage.$refs.editUserForm.resetFields();
      },
      rowClickUser(row, column, event) {
        this.selectItemData = row;
        this.selectItemIndex = row.index;
        this.getRolesByUserList(row);
        this.getFindAccountByID(row);
      },
      // 根据用户id获取角色列表
      getRolesByUserList(row) {
        let obj = {
          userid: row.id
        };
        _https.post.getFindRolesByUser(obj).then(res => {
          if (res.data.code == 0) {
            this.tableDataRole = res.data.data;
          }
        })
      },
      // 根据用户id获取配置列表
      getFindAccountByID(row) {
        let obj = {
          userId: row.id
        };
        _https.post.getFindAccountByID(obj).then(res => {
          if (res.data.code == 0) {
            this.tableDataSystem = res.data.data;
          } else {
            this.$message({type: 'error', message: res.data.message});
          }
        })
      },
      // 给用户新增角色
      addNewRole() {
        this.dialogEditRoles = true;
        let newArr = this.tableDataRole.map((item) => {
          return item.id
        });
        this.rolesForm.roles = newArr;
      },
      // 关闭添加角色弹窗的回调
      addRolesClose() {
        this.dialogEditRoles = false;
        this.resetRoles();
      },
      // 添加新角色保存
      addRolesKeep() {
        let obj = {
          userId: this.selectItemData.id,
          roleIds: this.rolesForm.roles.join(",")
        };
        _https.post.getUserAddRoles(obj).then(res => {
          if (res.data.code == 0) {
            this.$message({type: 'success', message: '新增角色成功!'});
            this.getRolesByUserList(this.selectItemData);
            this.dialogEditRoles = false;
            // this.resetRoles();
          }
        })
      },
      // 点击开通系统账户
      makeSysUser() {
        this.dialogSysUser = true;
      },
      // 关闭开通系统账户弹窗
      sysUserClose() {
        this.dialogSysUser = false;
        this.$refs.userManage.$refs.addSysUserForm.resetFields();
      },
      // 添加账户保存
      addSysUserKeep() {
        let sysUserForm = this.sysUserForm;
        let obj = {
          loginname: sysUserForm.name,
          password: sysUserForm.password,
          type: sysUserForm.type,
          oauthid: "",
          appid: "",
          belong: this.selectItemData.id,
          name: "",
          isshow: 1
        };

        this.$refs.userManage.$refs.addSysUserForm.validate((valid) => {
          if (!valid) {
            return;
          } else {
            if (sysUserForm.agamePassword != sysUserForm.password) {
              this.$message({
                type: 'error',
                message: '密码不一致!'
              });
              return
            }
            _https.post.getSaveAccount(obj).then(res => {
              if (res.data.code == 0) {
                this.$message({type: 'success', message: res.data.message});
                this.dialogSysUser = false;
                // this.$refs.userManage.$refs.addSysUserForm.resetFields();
                this.getFindAccountByID(this.selectItemData);
              } else {
                this.$message({type: 'error', message: res.data.message});
              }
            })
          }
        })
      },
      // 删除账户
      delSysUser(index, row) {
        let obj = {
          id: row.id
        };

        this.$confirm('此操作将永久删除该账户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _https.post.getDeleteAccount(obj).then(res => {
            if (res.data.code == 0) {
              this.$message({type: 'success', message: res.data.message});
              this.getFindAccountByID(this.selectItemData);
            } else {
              this.$message({type: 'error', message: res.data.message});
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });


      },
      // 编辑账户
      editSysUser(index, row) {
        this.dialogSysUserEdit = true;
        this.editSysUserInfo = row;
        this.sysUserForm = {
          name: row.loginname,
          type: row.type
        }
      },
      // 账户编辑窗口关闭回调
      sysUserEditClose() {
        this.dialogSysUserEdit = false;
        this.resetSysUser();
        this.$refs.userManage.$refs.editSysUserForm.resetFields();
      },
      // 账户编辑保存
      sysUserEditKeep() {
        let editSysUserInfo = this.editSysUserInfo;
        let sysUserForm = this.sysUserForm;
        let obj = {
          id: editSysUserInfo.id,
          loginname: sysUserForm.name,
          password: sysUserForm.password,
          time: editSysUserInfo.uptime,
          type: sysUserForm.type,
          oauthid: editSysUserInfo.oauthid,
          appid: editSysUserInfo.appid,
          belong: editSysUserInfo.belong,
          name: editSysUserInfo.name,
          // isshow: editSysUserInfo.isshow,
          isshow: "1",
          changepsd: 0
        };
        this.$refs.userManage.$refs.editSysUserForm.validate((valid) => {
          if (!valid) {
            return;
          } else {
            _https.post.getUpdateAccount(obj).then(res => {
              if (res.data.code == 0) {
                this.$message({type: 'success', message: res.data.message});
                this.getFindAccountByID(this.selectItemData);
                this.dialogSysUserEdit = false;
                // this.resetSysUser();
                // this.$refs.userManage.$refs.editSysUserForm.resetFields();
              } else {
                this.$message({type: 'error', message: res.data.message});
              }
            })
          }
        })
      },
      // 选择所属岗位的时候
      changeStation(arr) {
        this.joinStationList = [];
        this.userForm.inposition = "";
        let newArr = [];
        for (let i = 0; i < arr.length; i++) {
          if (this.keepStationMap.get(arr[i])) {
            newArr.push(this.keepStationMap.get(arr[i]));
          }
        }
        this.joinStationList = newArr;
      },
      /**
       * 判断是不是为空
       * @param obj
       */
      forEmtry(obj) {
        for (let item in obj) {
          if (obj[item] == '') {
            return false;
          }
        }
        return true;
      },
      // 清空初始化
      reset() {
        this.userForm = {
          desc: '',
          phone: '',
          station: []
        }
      },
      resetRoles() {
        this.rolesForm = {
          roles: ""
        }
      },
      resetSysUser() {
        this.sysUserForm = {
          name: "",
          password: "",
          agamePassword: "",
          type: ""
        }
      }

    },
    destroyed() {

    }
  }
</script>

<style scoped lang="less">

</style>
